<?php


namespace App\Exports;

use App\Models\RecordGoods;
use App\Models\RecordOrder;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Contracts\View\View;
/**
 * Created By FreeAbrams
 * Date: 2020/12/1
 */
class GoodsExport implements FromView
{
	protected $timeBetween;
	protected $sum = 0;
	
	public function __construct($timeBetween)
	{
		$this->timeBetween = $timeBetween;
	}
	
	public function view():View
	{
		$temp = $this->data($this->timeBetween);
		
		return view('admin.export.goods-export-table', ['data' => $temp, 'sum' => $this->sum]);
	}
	
	protected function data($timeBetween)
	{
		$store_id = Admin::user()->store_id;
		
		$goods = RecordGoods::with(['goods' => function($q) use($store_id){
			$q->withTrashed()->where('store_id', $store_id)->selectRaw('id, name');
		}])->whereBetween('created_at', $timeBetween)
			->where('type', '2')
			->get(['id', 'goods_id', 'number', 'created_at']);
		// 计算总数
		$this->sum = $goods->sum('number');
		// 增加分组列
		$goods = $goods->map(function ($item) {
			$date = New Carbon($item->created_at);
			$item->date = $date->format('m');
			return $item;
		});
		// 名称分组后date分组
		$goods = $goods->groupBy('goods.name')->map(function ($item) {
			return $item->groupBy('date');
		});
		
		return $goods;
	}
}